import dayjs from 'dayjs'
import { ElNotification } from 'element-plus'
import conference from '@/api/modules/conference'

export default function useEditConference(pid: number) {
  const conferenceDetail = reactive({
    id: pid,
    name: '',
    dataTimeRange: [new Date(), new Date()] as [Date, Date],
    position: '',
    status: 0,
  })

  function fetchData() {
    return conference.getDetail(pid).then((res) => {
      const { name, position, startTime, endTime, status } = res.data
      conferenceDetail.name = name
      conferenceDetail.position = position
      conferenceDetail.status = status
      conferenceDetail.dataTimeRange[0] = new Date(startTime)
      conferenceDetail.dataTimeRange[1] = new Date(endTime)
      return res.data
    })
  }

  function commitChange() {
    const { id, name, dataTimeRange, position, status } = conferenceDetail

    return conference.edit({
      id,
      name,
      status,
      position,
      startTime: dayjs(dataTimeRange[0]).format('YYYY-MM-DD HH:mm:ss'),
      endTime: dayjs(dataTimeRange[1]).format('YYYY-MM-DD HH:mm:ss'),
    })
  }

  function start(id: number) {
    conference.start(id).then(() => {
      conferenceDetail.status = 1
      ElNotification({
        title: '会议状态变更',
        message: `${conferenceDetail.name} 已开始`,
        type: 'success',
        duration: 3000,
      })
    })
  }

  function finish(id: number) {
    conference.finish(id).then(() => {
      conferenceDetail.status = 2
      ElNotification({
        title: '会议状态变更',
        message: `${conferenceDetail.name} 已结束`,
        type: 'success',
        duration: 3000,
      })
    })
  }

  return {
    conferenceDetail,
    fetchData,
    commitChange,
    start,
    finish,
  }
}
